//
//  AppDelegate.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/19.
//

import UIKit
import IQKeyboardManagerSwift
import Toast_Swift
import SwiftyJSON
import SnapKit
import SwiftyUserDefaults
import Alamofire
import AlamofireImage
import AuthenticationServices
import QCloudCOSXML

@main
class AppDelegate: UIResponder, UIApplicationDelegate,QCloudSignatureProvider {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        // 腾讯云对象存储
        let config = QCloudServiceConfiguration.init()
        let endpoint = QCloudCOSXMLEndPoint.init();
        // 替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.tencentcloud.com/cos5/bucket
        // COS支持的所有region列表参见https://www.qcloud.com/document/product/436/6224
        endpoint.regionName = AppConfig.sharedInstance.QCloudCOSRegionName;
        // 使用 HTTPS
        endpoint.useHTTPS = true;
        config.endpoint = endpoint;
        // 密钥提供者为自己
        config.signatureProvider = self;
        // 初始化 COS 服务示例
        QCloudCOSXMLService.registerDefaultCOSXML(with: config);
        QCloudCOSTransferMangerService.registerDefaultCOSTransferManger(
            with: config);

        //一键登录
        TXCommonHandler.sharedInstance().setAuthSDKInfo(AppConfig.sharedInstance.AtAuthKey, complete: nil)
        
        //其他方式登录
        NotificationCenter.default.addObserver(self, selector: #selector(AuthPageFunction(_:)), name: NSNotification.Name(AppConfig.sharedInstance.AuthPageFunctionNotification), object: nil)
        
        //键盘
        IQKeyboardManager.shared.enable = true
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0.0
        }
        
        //状态栏
        UINavigationBar.appearance().barStyle = .default
        
        //导航条样式
        let font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
        let textAttributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:AppConfig.sharedInstance.MAIN_TITLE_COLOR]
        (UINavigationBar.appearance()).isTranslucent = true
        (UINavigationBar.appearance()).titleTextAttributes = textAttributes
        (UINavigationBar.appearance()).tintColor = AppConfig.sharedInstance.MAIN_TITLE_COLOR
        (UINavigationBar.appearance()).barTintColor = UIColor.white
        (UINavigationBar.appearance()).shadowImage = UIImage.init()
        
        return true
    }
    
    // 获取签名的方法入口，这里演示了获取临时密钥并计算签名的过程
    // 您也可以自定义计算签名的过程
    func signature(with fileds: QCloudSignatureFields!,
        request: QCloudBizHTTPRequest!,
        urlRequest urlRequst: NSMutableURLRequest!,
        compelete continueBlock: QCloudHTTPAuthentationContinueBlock!) {

        //这里同步从后台服务器获取临时密钥
        APIManager.sharedInstance.getInfoFromOss { (result, error) in
            if error == nil {
                let secretID = result["data"].dictionaryObject?["tmpSecretId"] as! String
                let secretKey = result["data"].dictionaryObject?["tmpSecretKey"] as! String
                let token = result["data"].dictionaryObject?["sessionToken"] as! String
                let startTime = result["data"].dictionaryObject?["startTime"] as! String
                let endTime = result["data"].dictionaryObject?["endTime"] as! String

                let credential = QCloudCredential.init();
                // 临时密钥 SecretId
                // sercret_id替换为用户的 SecretId，登录访问管理控制台查看密钥，https://console.tencentcloud.com/cam/capi
                credential.secretID = secretID
                // 临时密钥 SecretKey
                // sercret_key替换为用户的 SecretKey，登录访问管理控制台查看密钥，https://console.tencentcloud.com/cam/capi
                credential.secretKey = secretKey
                // 临时密钥 Token
                // 如果使用永久密钥不需要填入token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见https://intl.cloud.tencent.com/document/product/436/14048
                credential.token = token
                /** 强烈建议返回服务器时间作为签名的开始时间, 用来避免由于用户手机本地时间偏差过大导致的签名不正确(参数startTime和expiredTime单位为秒)
                */
                credential.startDate = Date.init(timeIntervalSince1970: Double(startTime)!)
                credential.expirationDate = Date.init(timeIntervalSince1970: Double(endTime)!)


                let creator = QCloudAuthentationV5Creator.init(credential: credential);
                // 注意 这里不要对urlRequst 进行copy以及mutableCopy操作
                let signature = creator?.signature(forData: urlRequst);
                continueBlock(signature,nil);

            }
        }

    }

    
    @objc func AuthPageFunction(_ notification: Notification) {
        let data = JSON.init(notification.object!)
        if data["action"].stringValue == "OtherLoginWay" {
            if UtilManager.sharedInstance.getCurrentVc().navigationController?.classForCoder != LoginNavController.classForCoder() {
                let loginNav = UtilManager.sharedInstance.getVCFromSB(identifier: "LoginNavController") as! LoginNavController
                loginNav.modalPresentationStyle = .fullScreen
                (loginNav.viewControllers[0] as! AccountPassViewController).qrcode = data["qrcode"].stringValue
                (loginNav.viewControllers[0] as! AccountPassViewController).pageFrom = data["pageFrom"].stringValue
                UtilManager.sharedInstance.getCurrentVc().present(loginNav, animated: true, completion: nil)
            }
        } else if data["action"].stringValue == "LoginToTV" {
            let scan = ScanViewController.init()
            scan.scanResBlock = { scanRes in
                TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
                UserInfo.sharedInstance.toLogin("tv", scanRes)
            }
            
            let nav = UINavigationController.init(rootViewController: scan)
            nav.modalPresentationStyle = .fullScreen
            UtilManager.sharedInstance.getCurrentVc().present(nav, animated: true)
        } else if data["action"].stringValue == "loginToNormal" {
            TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
            UserInfo.sharedInstance.toLogin("normal")
        }
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }


}

